/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.formserver.vmmanager.service;

import com.inspur.edp.bff.engine.core.cache.BffEngineCacheService;
import com.inspur.edp.cef.entity.config.CefConfig;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.extendinfo.entity.GspVoExtendInfo;
import com.inspur.edp.formserver.viewmodel.extendinfo.entity.VoConfigCollectionInfo;
import com.inspur.edp.formserver.voextendinfo.server.api.GspVoExtendInfoRpcService;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.metadata.rtcustomization.spi.MetadataSavedToDBExtend;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class VOSavedToDBExtend implements MetadataSavedToDBExtend {

    private static final Logger logger = LoggerFactory.getLogger(VOSavedToDBExtend.class);
    @Override
    public void execute(GspMetadata gspMetadata, ProcessMode processMode) {
        logger.info("执行元数据扩展,ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
        GspVoExtendInfoRpcService service = SpringBeanUtils.getBean(GspVoExtendInfoRpcService.class);

        if(!"GSPViewModel".equals(gspMetadata.getHeader().getType())) {
            if(gspMetadata.getHeader().getType()==null||"".equals(gspMetadata.getHeader().getType())){
                logger.error("元数据Type为空，更新config信息失败！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
            }
            return;
        }
        if(gspMetadata.getContent() == null){
            logger.error("参数元数据content为null！！！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
        }
        GspVoExtendInfo existed = service.getVoExtendInfo(((GspViewModel)gspMetadata.getContent()).getId());
        if(existed != null) {
            logger.info("更新configInfo前删除重复,ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName());
            service.deleteVoExtendInfo(((GspViewModel)gspMetadata.getContent()).getId());
        }
        BffEngineCacheService.remove(gspMetadata.getHeader().getId());

        try {
            List<GspVoExtendInfo> infos = new ArrayList();
            GspViewModel vo = (GspViewModel) gspMetadata.getContent();
            GspVoExtendInfo info = buildVoExtendInfo(processMode, vo, existed);
            if (vo.getGeneratedConfigID()!=null) {
                infos.add(info);
                logger.info("开始更新VO元数据configInfo，ID:"+gspMetadata.getHeader().getId()+"....configid:"+info.getConfigId());
                service.saveGspVoExtendInfos(infos);
            }else{
                logger.error("ConfigId生成为null，更新config信息失败！！！！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName()+"....code:"+vo.getCode());
            }
        } catch (Exception e) {
            logger.error("部署VO元数据失败！！！！ID:"+gspMetadata.getHeader().getId()+"....name:"+gspMetadata.getHeader().getName()+"...异常信息："+e);
            throw new RuntimeException("部署解析VO元数据出错：", e);
        }
    }

    private GspVoExtendInfo buildVoExtendInfo(ProcessMode processMode, GspViewModel vo, GspVoExtendInfo existing) {
        GspVoExtendInfo info = new GspVoExtendInfo();
        VoConfigCollectionInfo voConfigCollectionInfo = getBffConfigCollectionInfo(vo);
        voConfigCollectionInfo.setProjectType(processMode);
        info.setVoConfigCollectionInfo(voConfigCollectionInfo);
        info.setId(vo.getID());
        info.setConfigId(vo.getGeneratedConfigID());;
        info.setCreatedOn(Date.from(CAFContext.current.getCurrentDateTime().toInstant()));
        info.setLastChangedOn(Date.from(CAFContext.current.getCurrentDateTime().toInstant()));
        if (!vo.getIsVirtual()) {
            info.setBeSourceId(vo.getMapping().getTargetMetadataId());
        }
        if (existing != null) {
            info.setLastChangedOn(Date.from(CAFContext.current.getCurrentDateTime().toInstant()));
        }
        return info;
    }

    private VoConfigCollectionInfo getBffConfigCollectionInfo(GspViewModel vo) {
        CefConfig cefConfig = new CefConfig();
        cefConfig.setID(vo.getGeneratedConfigID());
        cefConfig.setDefaultNamespace(vo.getCoreAssemblyInfo().getDefaultNamespace().toLowerCase());
        VoConfigCollectionInfo voConfigCollectionInfo = new VoConfigCollectionInfo();
        voConfigCollectionInfo.setConfig(cefConfig);
        return voConfigCollectionInfo;
    }

}
